/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React, { useEffect, useState } from 'react';
import { useAntdTable, useRequest } from 'ahooks';
import {
  Input,
  Form,
  Dropdown,
  Select,
  Button,
  Space,
  Menu,
  Row,
  Col,
  Modal,
  InputNumber,
  Radio,
  message,
  TableColumnsType,
  Tooltip,
} from 'antd';
import IAutoPage from '@/components/soa/IAutoPage';
import IAutoSearch from '@/components/soa/IAutoSearch';
import IAutoTable from '@/components/soa/IAutoTable';
import { DownOutlined } from '@ant-design/icons';
import {
  getHotScenesConfig,
  getLatestScenesConfig,
  getSceneCommunityList,
  saveHotScenesConfig,
  saveLatestScenesConfig,
} from '@/services/soa/sceneCommunity';
import styles from './index.less';
import { router } from 'umi';
import IAutoButton from '@/components/soa/IAutoButton';
import { get01Text, getDateTime } from '@/utils/soa/utils';
import { ISceneCommunityItem } from '@/types/sceneCommunity';
import { getSeriesModelList } from '@/services/soa/sceneOfficial';
import { connect } from 'dva';

const { Option } = Select;
const { useForm, Item } = Form;

const Index = (props: any) => {
  const {
    location: { pathname },
  } = props;
  const [form] = useForm();
  const [latestForm] = useForm();
  const [hotForm] = useForm();
  const [latestOpen, setLatestOpen] = useState(false);
  const [hotOpen, setHotOpen] = useState(false);
  const [withinDaysOfScenes, setWithinDaysOfScenes] = useState(0);
  const [amountOfLatestScenes, setAmountOfLatestScenes] = useState(0);
  const [options, setOptions] = useState([]);
  const [condition, setCondition] = useState(0);
  const [topDownload, setTopDownload] = useState(0);
  const { tableProps, run, pagination, refresh } = useAntdTable(getSceneCommunityList, {
    form,
  });
  // 车系车型
  const seriesModelList = useRequest(getSeriesModelList);
  const [latestScene, setLatestScene] = useState(null);
  const [hotScene, setHotScene] = useState(null);
  const [officialScene, setOfficialScene] = useState(null);

  const columns: TableColumnsType<ISceneCommunityItem> = [
    {
      title: '场景名',
      dataIndex: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '分类名称',
      dataIndex: 'categoryName',
      ellipsis: true,
    },
    {
      title: '是否最新场景',
      dataIndex: 'latestScene',
      width: 100,
      render: text => get01Text(text),
    },
    {
      title: '是否官方场景',
      dataIndex: 'officialScene',
      width: 100,
      render: (text: any) => get01Text(text),
    },
    {
      title: '是否热门场景',
      dataIndex: 'hotScene',
      width: 100,
      render: (text: any) => get01Text(text),
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      ellipsis: true,
    },
    {
      title: '车系',
      width: 100,
      dataIndex: 'seriesName',
      ellipsis: true,
    },
    {
      title: '车型',
      dataIndex: 'modelName',
      width: 250,
      ellipsis: true,
      render: (_, { modelName }) => {
        return (
          <Tooltip title={modelName}>
            <span className={styles.reasonSpan}>{modelName}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '审核时间',
      dataIndex: 'approveTime',
      width: 180,
      render: text => getDateTime(text),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: text => {
        return text === 0 ? (
          <span style={{ color: '#00A870' }}>发布成功</span>
        ) : (
          <span style={{ color: '#FF7918' }}>发布失败</span>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 90,
      render: (_, record) => {
        return (
          <IAutoButton
            onClick={() => gotoDetails(record.sceneRecordUuid)}
            pathname={pathname}
            auth={'sceneCommunity_doDetail'}
          >
            详情
          </IAutoButton>
        );
      },
    },
  ];

  useEffect(() => {
    props.dispatch({
      type: 'vehicleInfoQuery/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (e: any) => {
        form.setFieldsValue({ brandCode: e?.data?.[0]?.brandName });
      },
    });
  }, []);

  /**
   * @description 车系选择
   * @param value
   */
  const handleProvinceChange = (value: any) => {
    form.setFieldsValue({
      modelCode: undefined,
    });
    setOptions([]);
    for (const obj of seriesModelList?.data?.data || []) {
      if (value === obj?.code) {
        setOptions(obj.children);
      }
    }
  };

  const onFinish = (values: any) => {
    submitHotScenesConfig.run(values);
    setTopDownload(values?.topDownload);
  };
  const onFinishLast = (values: any) => {
    submitLatestScenesConfig.run({
      ...values,
    });
    setWithinDaysOfScenes(values?.withinDaysOfScenes);
    setCondition(values?.conditionValue);
    setAmountOfLatestScenes(values?.amountOfLatestScenes);
  };

  const gotoDetails = (sceneUuid: string) => {
    router.push({
      pathname: '/soaManage/sceneCommunity/scenecommunity_detail',
      query: { sceneRecordUuid: sceneUuid },
    });
  };

  const showLatestModal = () => {
    latestForm.resetFields();
    latestScenesConfig.run();
    setLatestOpen(true);
  };

  const hideLatestModal = () => {
    latestForm.resetFields();
    setLatestOpen(false);
  };

  const showHotModal = () => {
    hotForm.resetFields();
    hotScenesConfig.run();
    setHotOpen(true);
  };

  const hideHotModal = () => {
    hotForm.resetFields();
    setHotOpen(false);
  };

  //所有下拉发生改变的时候
  const changeSceneType = (value: any) => {
    setLatestScene(null);
    setHotScene(null);
    setOfficialScene(null);
    switch (value) {
      case '1': {
        setLatestScene(1);
        break;
      }
      case '2': {
        setOfficialScene(1);
        break;
      }
      case '3': {
        setHotScene(1);
        break;
      }
    }
  };

  const changeName = (value: any) => {
    form.setFieldsValue({
      name: value.target.value || undefined,
    });
  };

  // const changeBrandCode = (value: any) => {
  //   form.setFieldsValue({
  //     brandCode: value,
  //   });
  // };

  const onSearch = () => {
    run({
      ...pagination,
      current: 1,
      ...form.getFieldsValue(),
      latestScene,
      hotScene,
      officialScene,
    });
  };

  const latestScenesConfig = useRequest(getLatestScenesConfig, {
    // manual: true,
    onSuccess: res => {
      setWithinDaysOfScenes(res.data.withinDaysOfScenes);
      setAmountOfLatestScenes(res.data.amountOfLatestScenes);
      setCondition(res.data.conditionValue);
    },
  });

  const hotScenesConfig = useRequest(getHotScenesConfig, {
    // manual: true,
    onSuccess: res => {
      setTopDownload(res.data.topDownload);
    },
  });
  const submitLatestScenesConfig = useRequest(saveLatestScenesConfig, {
    manual: true,
    onSuccess: res => {
      if (res.statusCode === '0') {
        message.success('保存成功');
        hideLatestModal();
        refresh();
      }
    },
  });

  const submitHotScenesConfig = useRequest(saveHotScenesConfig, {
    manual: true,
    onSuccess: res => {
      if (res.statusCode === '0') {
        message.success('保存成功');
        hideHotModal();
        refresh();
      }
    },
  });

  useEffect(() => {
    seriesModelList.run();
  }, []);

  const menu = (
    <Menu>
      {/*<Menu.Item onClick={showLatestModal}>最新场景配置</Menu.Item>*/}
      {/*<Menu.Item onClick={showHotModal}>热门场景配置</Menu.Item>*/}
      <Menu.Item>
        <IAutoButton
          pathname={pathname}
          auth={'sceneCommunity_doNew'}
          type={'text'}
          onClick={showLatestModal}
          buttonType={'form'}
        >
          最新场景配置
        </IAutoButton>
      </Menu.Item>
      <Menu.Item>
        <IAutoButton
          pathname={pathname}
          auth={'sceneCommunity_doHot'}
          type={'text'}
          onClick={showHotModal}
          buttonType={'form'}
        >
          热门场景配置
        </IAutoButton>
      </Menu.Item>
    </Menu>
  );

  return (
    <div>
      <IAutoSearch>
        <Form name="search" form={form} layout={'inline'}>
          <Row className={styles.search} gutter={[8, 8]}>
            <Col flex="305px">
              <Item>
                <Input.Group compact>
                  <Item name={'allSelect'}>
                    <Select defaultValue="0" onChange={changeSceneType}>
                      <Select.Option value="0">所有</Select.Option>
                      <Select.Option value="1">最新</Select.Option>
                      <Select.Option value="2">官方</Select.Option>
                      <Select.Option value="3">热门</Select.Option>
                    </Select>
                  </Item>
                  <Item name="name">
                    <Input
                      placeholder={'请输入场景名称进行搜索'}
                      allowClear
                      onChange={changeName}
                      // suffix={<SearchOutlined onClick={onSearch} />}
                      // onPressEnter={onSearch}
                      maxLength={20}
                    />
                  </Item>
                </Input.Group>
              </Item>
            </Col>
            <Col sm={12} md={6}>
              <Item label={'品牌'} name="brandCode">
                {/*<Select*/}
                {/*  allowClear*/}
                {/*  style={{ width: 139 }}*/}
                {/*  placeholder={'请选择品牌'}*/}
                {/*  options={brandSelectOption}*/}
                {/*  onChange={changeBrandCode}*/}
                {/*/>*/}
                <Input disabled></Input>
              </Item>
            </Col>
            <Col sm={12} md={6}>
              <Item label={'车系'} name="seriesCode">
                <Select
                  style={{ width: '100%' }}
                  className={styles.itemWidth}
                  placeholder={'请选择车系'}
                  onChange={handleProvinceChange}
                  allowClear
                >
                  {seriesModelList?.data?.data?.map?.((obj: any) => (
                    <Option value={obj.code} key={obj.code}>
                      {obj.name}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col sm={12} md={6}>
              <Item label={'车型'} name="modelCode">
                <Select
                  style={{ width: '100%' }}
                  className={styles.itemWidth}
                  showArrow
                  placeholder={'请选择车型'}
                  // mode={'multiple'}
                  allowClear
                >
                  {options.map?.((obj: any) => (
                    <Option value={obj.code} key={obj.code}>
                      {obj.name}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col flex="auto" style={{ display: 'flex', justifyContent: 'end' }}>
              <IAutoButton
                htmlType={'submit'}
                buttonType={'form'}
                type={undefined}
                pathname={pathname}
                auth={'sceneCommunity_doSearch'}
                style={{ marginRight: 10 }}
                onClick={onSearch}
              >
                查询
              </IAutoButton>
              <Dropdown overlay={menu}>
                {/*<IAutoButton size={'small'} type={'primary'} buttonType={"form"} pathname={pathname} auth={"sceneCommunity_doEdit"}>*/}
                {/*  <Space>配置</Space>*/}
                {/*  <DownOutlined />*/}
                {/*</IAutoButton>*/}
                <Button size={'small'} type={'primary'}>
                  <Space>配置</Space>
                  <DownOutlined />
                </Button>
              </Dropdown>
            </Col>
          </Row>
        </Form>
      </IAutoSearch>
      <IAutoPage>
        <IAutoTable columns={columns} tableProps={tableProps} size="small" />
      </IAutoPage>

      <Modal
        title={'最新场景配置'}
        visible={latestOpen}
        onOk={() => latestForm.submit()}
        onCancel={hideLatestModal}
      >
        <Form
          form={latestForm}
          onFinish={onFinishLast}
          initialValues={{
            withinDaysOfScenes,
            amountOfLatestScenes,
            conditionValue: condition,
          }}
        >
          <Row>
            <Item
              name="withinDaysOfScenes"
              label={'设定近'}
              colon={false}
              rules={[
                {
                  required: true,
                  message: '请输入天数',
                },
              ]}
            >
              <InputNumber
                style={{ width: 66 }}
                value={withinDaysOfScenes}
                max={100}
                min={1}
                defaultValue={30}
              />
            </Item>
            <Item>
              <span style={{ marginLeft: 10 }}>日内发布的场景</span>
            </Item>
          </Row>
          <Item name="conditionValue">
            {/*<Radio.Group defaultValue={condition}>*/}
            <Radio.Group defaultValue={0}>
              <Radio value={0}>且</Radio>
              <Radio value={1}>或</Radio>
            </Radio.Group>
          </Item>
          <Row>
            <Item
              name="amountOfLatestScenes"
              label={'设定最新发布的'}
              colon={false}
              rules={[
                {
                  required: true,
                  message: '请输入条数',
                },
              ]}
            >
              <InputNumber
                style={{ width: 66 }}
                value={amountOfLatestScenes}
                max={100}
                min={1}
                defaultValue={20}
              />
            </Item>
            <Item>
              <span style={{ marginLeft: 10 }}>条场景</span>
            </Item>
          </Row>
        </Form>
      </Modal>

      <Modal
        title={'热门场景配置'}
        visible={hotOpen}
        onCancel={hideHotModal}
        onOk={() => hotForm.submit()}
      >
        <Form form={hotForm} onFinish={onFinish} initialValues={{ topDownload }}>
          <Row>
            <Item
              name="topDownload"
              label={'设定下载量最多的'}
              rules={[
                {
                  required: true,
                  message: '请输入条数',
                },
              ]}
            >
              <InputNumber style={{ width: 66 }} value={topDownload} max={100} min={1} />
            </Item>
            <Item>
              <span style={{ marginLeft: 10 }}>条场景</span>
            </Item>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default connect(({ vehicleInfoQuery }: { vehicleInfoQuery: any }) => ({
  vehicleInfoQuery: vehicleInfoQuery,
}))(Index);
